import classNames from 'classnames';
import styles from '@/app/[locale]/home/home.module.scss';
import Image from 'next/image';
import { getCover } from '@/lib/tool';
import Link from 'next/link';
import type { IPost } from '@/interfaces';
import { useContext } from 'react';
import { HomePageContext } from '@/contexts/home';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import { AppContext } from '@/contexts/app';
import { useQuery } from '@tanstack/react-query';
import { queryPostRandom } from '@/services/api';
import useToast from '@/hooks/useToast';

export default function RightHome() {
  return (
    <div
      className={classNames(
        'd-none d-lg-block col-2 me-2 position-sticky overflow-y-auto mt-4',
        styles.pc_right,
      )}
    >
      <div className="vstack gap-4">
        <ShortcutBtn />
        <RelatedPost />
        <Footer />
      </div>
    </div>
  );
}

const ShortcutBtn = () => {
  const { translatedFields, source } = useContext(HomePageContext)!;
  const isLogin = !!source.path.user;

  return (
    <div className="row">
      <div className="col px-0 vstack gap-2">
        {isLogin ? (
          <Link href="/posts/new" className="btn btn-primary">
            <i className="bi bi-plus-lg me-2"></i>
            {translatedFields.createPost}
          </Link>
        ) : (
          <>
            <Link href="/login" className="btn btn-primary">
              <i className="bi bi-person me-2"></i>
              {translatedFields.loginNow}
            </Link>
            <Link href="/register" className="btn btn-primary">
              <i className="bi bi-person-add me-2"></i>
              {translatedFields.quickRegister}
            </Link>
          </>
        )}
      </div>
    </div>
  );
};

const RelatedPost = () => {
  const { show } = useToast();
  const { source, translatedFields } = useContext(HomePageContext)!;
  const appContext = useContext(AppContext);
  const metadata = appContext.metadata!;
  const env = metadata.env;

  const queryPostRandomQuery = useQuery(
    ['/forum', '/posts', '/random'],
    async () => {
      return (await queryPostRandom()) as IPost[];
    },
    {
      initialData: source.randomPosts,
    },
  );

  async function onClickRefresh() {
    try {
      await queryPostRandomQuery.refetch({ throwOnError: true });

      show({
        type: 'PRIMARY',
        message: translatedFields.changeBatchComplete,
      });
    } catch (e) {
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  return (
    <div className="row">
      <div className="col px-0">
        <div className="card border-0">
          <div className="card-body vstack gap-3">
            <div className="d-flex align-items-center fs-5 gap-2 fw-semibold">
              {translatedFields.relatedArticles}
            </div>

            {queryPostRandomQuery.data.length > 0 && (
              <div className="vstack gap-2">
                {queryPostRandomQuery.data.map((item) => {
                  return (
                    <Link
                      title={item.overview ? item.overview : item.name}
                      key={item.id}
                      href={`/posts/${item.id}`}
                      className="text-reset text-decoration-none"
                    >
                      <div
                        className={classNames(
                          'd-flex gap-2 rounded pe-2',
                          styles.pc_right_post,
                        )}
                      >
                        <div
                          className="d-flex rounded justify-content-center align-items-center flex-shrink-0 yw-bg ratio ratio-4x3 overflow-hidden"
                          style={{ width: 112, height: 84 }}
                        >
                          {item.cover ? (
                            <Image
                              className="rounded object-fit-contain"
                              src={getCover(item.cover, metadata)}
                              alt={item.name}
                              width={112}
                              height={84}
                              placeholder="blur"
                              blurDataURL={env.APP_BLUR_DATA_URL}
                            />
                          ) : (
                            <i className="bi bi-journal-text fs-2 d-flex justify-content-center align-items-center"></i>
                          )}
                        </div>
                        <div
                          className="flex-grow-1 overflow-hidden vstack gap-2 justify-content-evenly"
                          style={{ height: 84 }}
                        >
                          <div className="text-truncate">{item.name}</div>
                          {item.overview && (
                            <div
                              className="text-truncate small text-secondary"
                              dangerouslySetInnerHTML={{
                                __html: item.overview,
                              }}
                            ></div>
                          )}
                        </div>
                        <div className="align-self-center">
                          <i className="bi bi-arrow-right"></i>
                        </div>
                      </div>
                    </Link>
                  );
                })}
              </div>
            )}

            {queryPostRandomQuery.data.length === 0 && <Nodata />}

            <button
              disabled={
                queryPostRandomQuery.data.length === 0 ||
                queryPostRandomQuery.isLoading
              }
              onClick={onClickRefresh}
              type="button"
              className="btn text-secondary-emphasis mt-4 mb-3"
            >
              {queryPostRandomQuery.isLoading ? (
                <span
                  className="spinner-border spinner-border-sm me-2"
                  role="status"
                  aria-hidden="true"
                ></span>
              ) : (
                <i className="bi bi-arrow-clockwise me-2"></i>
              )}
              {translatedFields.changeBatch}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

const Footer = () => {
  const {
    source: { path },
    translatedFields,
  } = useContext(HomePageContext)!;
  const appContext = useContext(AppContext);
  const env = appContext.metadata!.env;

  return (
    <>
      {path.siteConfig &&
        Object.values(path.siteConfig).filter((item) => item).length > 1 && (
          <div className="row">
            <div className="col px-0">
              <div className="card border-0">
                <div className="card-body">
                  {path.siteConfig.mpImageLink && (
                    <div className="row">
                      <div className="col">
                        <div className="ratio ratio-16x9">
                          <Image
                            className="rounded object-fit-contain"
                            src={path.siteConfig.mpImageLink}
                            alt="miniProgramCode"
                            width={652}
                            height={240}
                            placeholder="blur"
                            blurDataURL={env.APP_BLUR_DATA_URL}
                          />
                        </div>
                      </div>
                    </div>
                  )}

                  <div className="row row-cols-2 g-3">
                    {path.siteConfig.helpLink && (
                      <div className="col">
                        <Link
                          href={path.siteConfig.helpLink}
                          className="text-secondary text-decoration-none text-decoration-underline-hover"
                        >
                          <i className="bi bi-question-circle me-2"></i>
                          {translatedFields.help}
                        </Link>
                      </div>
                    )}
                    {path.siteConfig.feedbackLink && (
                      <div className="col">
                        <Link
                          href={path.siteConfig.feedbackLink}
                          className="text-secondary text-decoration-none text-decoration-underline-hover"
                        >
                          <i className="bi bi-chat-square-text me-2"></i>
                          {translatedFields.feedback}
                        </Link>
                      </div>
                    )}
                    {path.siteConfig.reportLink && (
                      <div className="col">
                        <Link
                          href={path.siteConfig.reportLink}
                          className="text-secondary text-decoration-none text-decoration-underline-hover"
                        >
                          <i className="bi bi-flag me-2"></i>
                          {translatedFields.report}
                        </Link>
                      </div>
                    )}
                    {path.siteConfig.githubLink && (
                      <div className="col">
                        <a
                          rel="noreferrer"
                          target="_blank"
                          className="text-secondary text-decoration-none text-decoration-underline-hover"
                          href={path.siteConfig.githubLink}
                        >
                          <i className="bi bi-github me-2"></i>
                          Github
                        </a>
                      </div>
                    )}
                  </div>

                  <div className="my-2"></div>
                </div>
              </div>
            </div>
          </div>
        )}
    </>
  );
};
